<template>
  <div class="app-select" @click="showOption()">
    <div class="app-option" selected ref="self">{{label}}</div>
    <div class="app-option-container" :position="position" v-show="isOptiosShow">
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  data () { return { label: '', isOptiosShow: false } },
  props: { value: [String, Number], position: String },
  model: {
    event: 'change',
    prop: 'value'
  },
  mounted () { this.init() },
  methods: {
    init () {
      document.addEventListener('click', (e) => {
        if (e.target !== this.$refs.self) {
          this.isOptiosShow = false
        }
      })
      const VueObj = this
      this.$children.forEach(item => {
        if (item.$options._componentTag === 'app-option') {
          const optionClickHandlerEvents = item._events['optionClickHandler']
          if (optionClickHandlerEvents) {
            optionClickHandlerEvents.push(VueObj.optionClickHandler)
          } else {
            item._events['optionClickHandler'] = [VueObj.optionClickHandler]
          }
          if (VueObj.value === item.value) {
            VueObj.label = item.label
            item.active = true
          }
        }
      })
    },
    showOption () {
      this.isOptiosShow = true
    },
    optionClickHandler (option) {
      this.value = option.value
      this.label = option.label
      const VueObj = this
      this.$children.forEach(item => {
        if (item.$options._componentTag === 'app-option') {
          if (VueObj.value === item.value) {
            item.active = true
          } else {
            item.active = false
          }
        }
      })
      this.$emit('change', option.value)
    }
  }
}
</script>
